package com.pinyougou.user.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.pinyougou.common.util.HttpClientUtils;
import com.pinyougou.mapper.UserMapper;
import com.pinyougou.pojo.User;
import com.pinyougou.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service(interfaceName = "com.pinyougou.service.UserService")
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Value("${sms.url}")
    private String smsUrl;
    @Value("${sms.signName}")
    private String signName;
    @Value("${sms.templateCode}")
    private String templateCode;

    /**
     * 添加方法
     *
     * @param user
     */
    @Override
    public void save(User user) {
        try{
            // 设置密码(md5)
            user.setPassword(DigestUtils.md5Hex(user.getPassword()));
            // 设置创建时间
            user.setCreated(new Date());
            // 设置修改时间
            user.setUpdated(user.getCreated());
            userMapper.insertSelective(user);
        }catch (Exception ex){
            throw new RuntimeException(ex);
        }
    }

    /**
     * 修改方法
     *
     * @param user
     */
    @Override
    public void update(User user) {

    }

    /**
     * 根据主键id删除
     *
     * @param id
     */
    @Override
    public void delete(Serializable id) {

    }

    /**
     * 批量删除
     *
     * @param ids
     */
    @Override
    public void deleteAll(Serializable[] ids) {

    }

    /**
     * 根据主键id查询
     *
     * @param id
     */
    @Override
    public User findOne(Serializable id) {
        return null;
    }

    /**
     * 查询全部
     */
    @Override
    public List<User> findAll() {
        return null;
    }

    /**
     * 多条件分页查询
     *
     * @param user
     * @param page
     * @param rows
     */
    @Override
    public List<User> findByPage(User user, int page, int rows) {
        return null;
    }

    /** 发送短信验证码 */
    public boolean sendCode(String phone){
        try{
            // 1. 随机生成6位数字的短信验证码 commons-lang3.jar
            String msacode = RandomStringUtils.randomNumeric(6);
            System.out.println("code: " + msacode);

            // 2. 调用短信接口发送短信
            // 创建Http客户端工具对象
            HttpClientUtils httpClientUtils = new HttpClientUtils(false);
            // 定义Map集合封装请求参数
            Map<String, String> params = new HashMap<>();
            params.put("phone", phone);
            params.put("signName", signName);
            params.put("templateCode", templateCode);
            params.put("templateParam", "{'code' : '"+ msacode +"'}");
            // 发送post请求
            String res = httpClientUtils.sendPost(smsUrl, params);
            System.out.println("res = " + res);

            // 3. 如果发送成功，短信验证码存储到Redis(key: phone value:验证码) 有效时间90秒
            Map<String,Object> data = JSON.parseObject(res, Map.class);
            boolean success = (boolean)data.get("success");
            if (success){
                redisTemplate.boundValueOps(phone).set(msacode, 90, TimeUnit.SECONDS);
            }
            return success;
        }catch (Exception ex){
            throw new RuntimeException(ex);
        }
    }


    //保存的时候验证 验证码是否正确
    @Override
    public boolean checkSmsCode(String phone, String code) {
        String sysCode = redisTemplate.boundValueOps(phone).get();
        return StringUtils.isNoneBlank(sysCode)&&sysCode.equals(code);
    }
}






